﻿using Blog.Core.Domain.Model.User;
using Blog.Core.DTO.ViewModel;
using Blog.Core.DTO.ViewModel.User;
using Blog.Core.IRepositories.IUser;
using Blog.Core.IServices.IUser;
using Blog.Core.Repositories.User;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Blog.Core.DTO;
using Blog.Core.DTO.Helper;
using Blog.Core.IServices;
using Blog.Core.Repositories;
using System.Security.Claims;
using Microsoft.IdentityModel.JsonWebTokens;
using Blog.Core.IRepositories.JWT;
using Microsoft.AspNetCore.Authorization;
using Blog.Core.Api.Middleware;
using Newtonsoft.Json;//序列化
using Blog.Core.Services.User;
using Microsoft.OpenApi.Extensions;
using CSRedis;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Xml.Linq;
using Blog.Core.IRepositories;
using Blog.Core.Api.HostedService;
using Quartz.Impl;
using Quartz;
using System.Reflection;

namespace Blog.Core.Api.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [Route("api/[controller]/[action]")]

    [ApiController]
    public class UserController : BaseController<UserInfo>
    {
        //private readonly HttpContext context;
        //private readonly RequestLogMiddleware requestLogMiddleware;
        CSRedis.CSRedisClient _client=new CSRedisClient("127.0.0.1:6379");
        private readonly IUserService userServices;
        private readonly ITokenHelper _tokenHelper;
        public UserController(IBaseService<UserInfo> baseService, IUserService userServices, ITokenHelper tokenHelper) : base(baseService)
        {
            this.userServices = userServices;
            _tokenHelper = tokenHelper;
        }
        /// <summary>
        /// 反射获取数据值
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public IActionResult TsetReflection(string typeName)
        {
            //查找程序集中的所有类型名字，与typeName进行匹配
            Type t = Assembly.Load("Blog.Core.Services").GetTypes().Where(x => x.Name == typeName).FirstOrDefault();
            if (t == null)
            {
                return BadRequest();
            }
            //todo：调查一下怎么获得类里面懂得构造函数名称和私有字段
            //var list = t.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);//获取所有树形信息
            var list = t.GetConstructors();
            foreach (var item in list)
            {
                Console.WriteLine("字段名：" + item.Name);
            }
            List<string> names = list.Select(x => x.Name).ToList(); //用Linq把所有属性名转换为一个集合
            return Ok(names);

        }
        /// <summary>
        /// 输入一个类型的数据，能够自动转换成SQL（以下这个例子，做添加操作）
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public IActionResult TestORM(Roles entity)
        {
            //获取输入参数的类型Type
            Type t = entity.GetType();
            //获取t中的所有属性名称
            var props = t.GetProperties();
            //拼接添加的SQL语句
            string strSql = $"INSERT INTO {t.Name}s VALUES(";
            //循环props获取值
            foreach (var p in props)
            {
                string strValue = p.GetValue(entity).ToString();
                strSql += strValue + ",";
            }
            strSql = strSql.TrimEnd(',');
            strSql += ")";
            Console.WriteLine(strSql);
            return Ok(strSql);
        }
        /// <summary>
        /// TsetIOC容器
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public IActionResult TsetIOC(string typeName)
        {
            //输入类型目标

            return Ok();
        }
        /// <summary>
        /// 测试托管服务
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("TestQuartZ")]
        public async Task<IActionResult> TestQuartZ()
        {
            //1. 创建一个调度器
            var scheduler = await new StdSchedulerFactory().GetScheduler();
            await scheduler.Start(); //启动
                                     //2. 创建一个工作任务
            var job = JobBuilder.Create<FirstJob>().Build();
            ////3. 创建一个简单触发器
            //var trigger = TriggerBuilder.Create()
            //.WithSimpleSchedule(x =>{
            // x.WithRepeatCount(3) //循环次数
            // .WithIntervalInSeconds(1);//间隔时间
            //}).Build();
            //3. 创建Cron触发器（Cron触发器比简单触发器更加强大）
            var trigger = TriggerBuilder.Create()
            .WithCronSchedule("* * * * * ? *")
            .Build();
            //将三个对象，连接在一起
            await scheduler.ScheduleJob(job, trigger);
            return Ok();
        }



        /// <summary>
        /// 用户修改（管理员进行修改）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPut]
        public async Task<IActionResult> PutUserInfos(RoleUserDTO dto)
        {
            if (dto == null)
            {
                return Ok("参数错误！");
            }
            return Ok(await userServices.PutUserInfos(dto));
        }
        /// <summary>
        /// 删除（管理员删除（删除用户））
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        
        [AllowAnonymous]
        [HttpDelete]
        public async Task<IActionResult> DeleteUserInfo(int id)
        {
            if (id == 0)
            {
                return Ok("参数错误！");
            }
            return Ok(await userServices.DeleteUserInfo(id));
        }
        /// <summary>
        /// 删除（个人进行删除（账号注销））
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        [AllowAnonymous]
        [HttpDelete]
        public async Task<IActionResult> DeleteUserInfos(GetUserDeleteDTO dto)
        {
            if(dto==null)
            {
                return Ok("参数错误！");
            }
            if (dto.Id == 0)
            {
                return Ok("参数错误！");
            }
            return Ok(await userServices.DeleteUserInfos(dto));
        }


        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> UserLogin(PostUserLoginDTO dto, [FromServices] JwtTokenHelper _jwtTokenHelper)
        {
            var result = new ResponseModel();
            if (!ModelState.IsValid)
            {
                return BadRequest();
            }
            var user = await userServices.UserLogin(dto);
			if (user.Code == ResultStatusCode.SUCCESS)
            {
                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
                {
					{"Userid",user.Data.Id.ToString() },
					{ "LoginName",user.Data.Login  },
                    { "SuperAdmin", "true"}, //假定用户属于SuperAdmin角色
                };
                result.Code = 200;
                result.Data = user.Data;
                result.Msg = "登录成功";
                //（2） 后端：帮助类来生成JWT字符串，JWT字符串返回给浏览器
                result.TokenInfo = _tokenHelper.CreateToken(keyValuePairs, user.Data.Id);
				_client.HSet(user.Data.Id.ToString(), user.Data.Login, result.TokenInfo);
				return Ok(result);
            }
            else
            {
                result.Code = 401;
                result.Msg = user.Message;
            }
            return Unauthorized(result); //401的错误码

        }
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> PostUserInfo(RequestUserDTO entity)
        {
            if (entity == null)
            {
                return Ok("参数错误！");
            }
            return Ok(await userServices.PostUserInfo(entity));
        }


        /// <summary>
        /// 用户密码修改
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPut]
        public async Task<IActionResult> PutUserPwd(UserInfo entity)
        {
            if (entity == null)
            {
                return Ok("参数错误！");
            }
            return Ok(await userServices.PutUserPwd(entity));
        }
        /// <summary>
        /// 用户列表
        /// </summary>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<IActionResult> GetUserInfo(string? name, int pageindex = 1, int pagesize = 3)
        {
            ResponseResultDTO<PageDTO<GetUserInfoDTO>> result = new ResponseResultDTO<PageDTO<GetUserInfoDTO>>();
            var data = await userServices.GetUserInfo(pageindex, pagesize);
            if (!string.IsNullOrEmpty(name))
            {
                data.Plist = data.Plist.Where(x => x.UserName.Contains(name)).ToList();
            }
            result.Code = ResultStatusCode.SUCCESS;
            result.Message = "成功";
            result.Data = data;
            return Ok(result);
        }
        /// <summary>
        /// 修改用户个人信息（用户本人修改）
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPut]
        public async Task<IActionResult> PutUserInfo(UserInfo entity)
        {
            //判断参数是否为空
            if(entity==null)
            {
                return BadRequest();//如果为空
            }
            return Ok(await userServices.PutUserInfo(entity));
        }
        /// <summary>
        /// 获取用户单条信息（用于用户编辑个人信息使用）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<IActionResult> GetUserInfoById(int id)
        {
            //判断参数是否存在
            if(id==null)
            {
                return BadRequest();
            }
            ResponseResultDTO<GetUserInfoDTO> result = new ResponseResultDTO<GetUserInfoDTO>();
            var data = await userServices.GetUserInfoById(id);
            result.Code = ResultStatusCode.SUCCESS;
            result.Data = data;
            result.Message = "成功";
            return Ok(result);
        }
        /// <summary>
        /// 图片上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public IActionResult PicLoad(IFormFile file)
        {
            return Ok(PicHelper.UpLoad(file));
        }
        /// <summary>
        /// 令牌刷新
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public IActionResult TokeComparison(string name,int id)
        {
			var result = new ResponseModel();
			
            bool Flage = false;
            string key = id.ToString();
            var data = _client.HGetAll<TnToken>(key);
            if (data.Values != null)
            {
                Flage = true;
            }
            if (Flage)
            {

                Dictionary<string, string> keyValuePairs = new Dictionary<string, string>
                {
                    {"Userid",id.ToString() },
                    { "LoginName",name  },
                    { "SuperAdmin", "true"}, //假定用户属于SuperAdmin角色
                };
                result.Code = 200;
                result.Msg = "刷新成功";
                //（2） 后端：帮助类来生成JWT字符串，JWT字符串返回给浏览器
                result.TokenInfo = _tokenHelper.CreateToken(keyValuePairs,id);
                _client.HSet(id.ToString(), name, result.TokenInfo);

            }
            return Ok(result);
        }
        /// <summary>
        /// 获取用户的权限
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<dynamic> GetUserPermissions(string UserName)
        {
            ResponseResultDTO<List<MenuTreeDto>> responseResult = new ResponseResultDTO<List<MenuTreeDto>>();
            responseResult.Code = ResultStatusCode.SUCCESS;
            responseResult.Data = await userServices.GetFunctionsByUserId(UserName);
            responseResult.Message = "成功";
            return Ok(responseResult);
        }
        /// <summary>
        /// 测试权限1.0
        /// </summary>
        /// <returns></returns>
        [HttpGet("[action]")]
        [Authorize(Policy = "Permission")]
        public ActionResult<IEnumerable<string>> GetAdminValue()
        {
            return new string[] { "use Policy = Permission" };
        }
        /// <summary>
        /// 测试权限2.0
        /// </summary>
        /// <returns></returns>
        [HttpGet("[action]")]
        [Authorize(Policy = "Permission")]
        public ActionResult<IEnumerable<string>> GetGuestValue()
        {
            return new string[] { "use Policy = Permission" };
        }
    }
}
